import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:liuxlcommon/view/my_box.dart';
import 'package:love_newf/app/com/model/live_msg_type.dart';
import 'package:love_newf/app/com/model/room_data_model.dart';
import 'package:love_newf/app/com/model/user_info_model.dart';
import 'package:love_newf/app/com/util/gift_utils.dart';
import 'package:love_newf/app/com/view/label/sex_label.dart';
import 'package:love_newf/app/com/view/label/vip_grade_label.dart';
import 'package:love_newf/app/page/live/live_logic.dart';
import 'package:love_newf/generated/assets.dart';
import 'package:love_newf/value/app_colors.dart';
import 'package:love_newf/value/app_const.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_text_elem.dart';

import 'child_chat_logic.dart';

class ChildChatPage extends StatefulWidget {
  const ChildChatPage({Key? key}) : super(key: key);

  @override
  State<ChildChatPage> createState() => _ChildChatPageState();
}

class _ChildChatPageState extends State<ChildChatPage> {
  final ChildChatLogic logic = Get.put(ChildChatLogic());

  @override
  void initState() {
    super.initState();
    var v = V2TimMessage(elemType: LiveMsgType.TIP);
    v.textElem = V2TimTextElem(
        text:
            "平台公示:我们提倡绿色文明直播，直播内容以及封面、头像等不允许包含吸烟、辱骂，低俗，恐怖、诱惑、暴露等行为，否则将被封号处理。官方24小时在线巡查。");
    logic.list.add(v);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ChildChatLogic>(
        //更新比较频繁，所以要做成局部刷新。
        builder: (l) => LContainer(
            child: ListView.builder(
                controller: logic.scrollController,
                itemCount: logic.list.length,
                itemBuilder: (context, position) {
                  return itemView(position);
                })).padding(left: 10.w, bottom: 10.w));
  }

  itemView(int position) {
    V2TimMessage item = logic.list[position];

    if (item.elemType == MessageElemType.V2TIM_ELEM_TYPE_TEXT ||
        item.elemType == LiveMsgType.GIFT) {
      return itemTextView(item);
    }
    // if (item.elemType == tipElemType)
    return LText.easy(item.textElem!.text, 16.w, null, Colors.white)
        .paddingAll(12.w);
  }

  itemTextView(V2TimMessage item) {
    UserInfoModel sendUser;
    if (item.elemType == MessageElemType.V2TIM_ELEM_TYPE_TEXT) {
      var customData = json.decode(item.cloudCustomData!);
      sendUser =
          UserInfoModel.fromJson(json.decode(customData["sendUserInfo"]));
    } else {
      // item.elemType == LiveMsgType.GIFT
      RoomDataModel data =
          RoomDataModel.fromJson(json.decode(item.textElem!.text ?? ""));
      sendUser = data.givePropMsg!.sendUserVO!;
    }

    return LRow.eazy([
      LImage.easy(sendUser.avatar, 32.w, 32.w,32.w).onTapL((){
       LiveLogic.logic?.sendGiftDialog.show(userId: sendUser.userId.toString(),headImg: sendUser.avatar);

      }),
      8.lsw,
      LExpand(
        child: Wrap(spacing: 3.w, runSpacing: 5.w, children: [
          VipGradeLabel(sendUser.vipGrade),
          SexAgeLabel(sendUser.sex, sendUser.age).marginOnly(top: 2.w),
          ...userLabels(sendUser.userLabels),
          LText.easy(sendUser.nick, 13.sp, fw6, const Color(0xFFFF8DB7))
              .padding(right: 5.w),
          ...content(item)
        ]),
      )
    ])
        .margin(top: 8.w)
        .radius(12.w)
        .bgColor(const Color(0x24000000))
        .padding(left: 5.w, right: 5.w, top: 10.w, bottom: 10.w);
  }

  List<Widget> content(V2TimMessage item) {
    if (item.elemType == MessageElemType.V2TIM_ELEM_TYPE_TEXT) {
      return [LText.easy(item.textElem!.text, 13.sp, fw6, Colors.white)];
    } else {
      //礼物类型
      RoomDataModel data =
          RoomDataModel.fromJson(json.decode(item.textElem!.text ?? ""));
      var give = data.givePropMsg!;
      return [
        LText.easy("送给", 14.sp, fw6, AppColors.primaryColor),
        LText.easy(give.receiveNick, 14.sp, fw6, AppColors.secondColor),
        LText.easy(GiftUtils.propName(give.propId), 14.sp, fw6,
            AppColors.primaryColor),
        LText.easy("(${GiftUtils.getPropPrice(give.propId)}玫瑰)x${give.amount}",
            14.sp, fw6, AppColors.primaryColor),
        if (GiftUtils.getProp(give.propId) == null)
          LText.easy("新礼物，点击查看", 14.sp, fw6, AppColors.primaryColor).onTapL(() {
            GiftUtils.roomPropList.then((v) {
              logic.update();
            });
          }),
      ];
    }
  }

  List<Widget> userLabels(List<UserInfoUserLabels> labels) {
    return [
      for (var label in labels)
        LStack([
          if (label.labelType == 5)
            LText.easy(label.labelName, 10.w, fw5, const Color(0xFFFF536C))
                .margin(left: 5.w, top: 4.w)

                .gradient(const [Color(0xFFFFCDD6), Color(0xFFFFEFBF)],
                    Alignment.centerRight)
                .radius(28.w)
                .padding(top: 1.w, bottom: 1.w, left: 20.w, right: 5.w)
          else
            LText.easy(label.labelName, 10.w, fw5, Colors.white)
                .margin(left: 15.w, top: 7.w)
                .gradient(const [Color(0xFFFA5061), Color(0xFFFF59AD)],
                    Alignment.centerRight)
                .radius(28.w)
                .padding(top: 1.w, bottom: 1.w, left: 20.w, right: 5.w),
          if (label.labelType == 5)
            LImage.easy(Assets.liveShouhu, 22.w, 25.w)
          else
            LImage.easy(Assets.liveQinglv, 26.w, 35.w),
        ])
    ];
  }

  @override
  void dispose() {
    Get.delete<ChildChatLogic>();
    super.dispose();
  }
}
